<template>
    <fieldset>
        <legend>全选反选</legend>
        <b>全选</b>
        <input type="checkbox" v-model="checked">
        <ul>
            <li v-for="item in arr" :key="item.id">
                <input type="checkbox" v-model="models" :value="item">
                <b>{{item.item}}</b>
            </li>
        </ul>
        <h3>{{models}}</h3>
    </fieldset>
</template>

<script>
    export default {
        data() {
            return {
                checked: false,
                models: [],
                arr: [
                    {
                        id: 1,
                        item: '学vue'
                    },
                    {
                        id: 2,
                        item: '学react'
                    },
                    {
                        id: 3,
                        item: '学hook'
                    }
                ]
            }
        },
        mounted() {
            // setTimeout(() => {
            //     this.models = this.arr;
            // }, 2000)
        },
        // computed: {
        //     checked() {
        //         return false 
        //     }
        // },
        watch: {
            checked(newChecked) {
                // console.log(newVal)
                if (newChecked) {
                    //全选被勾选了
                    //其它的item勾选
                    this.models = this.arr;
                } else {
                    // 取消其中一个item,不执行这句话
                    if (this.models.length === this.arr.length) {
                        this.models = []
                    }
                }
            },
            models(models) {
                if (models.length === this.arr.length) {
                    this.checked = true
                } else {
                    this.checked = false
                }
            }
        }
    }
</script>